<template>
    <el-dialog v-model="openSettingVisible" title="配置数据集" align-center :before-close="handleBeforeClose" class="setting-dialog" width="500px">
        <div class="dataset-panel">
            <div class="dataset-name">{{ datasetInfo.dataset_name }}</div>
            <div class="dataset-tags">
                <el-tag class="dataset-tag" type="success">{{ datasetInfo.id }}</el-tag>
                <el-tag class="dataset-tag" type="warning">{{ datasetInfo.dataset_type }}</el-tag>
                <el-tag class="dataset-tag" type="warning">{{ datasetInfo.label_format }}</el-tag>
            </div>
            <div class="dataset-info">
                <div class="dataset-prop">
                    <div class="dataset-title">样本目录</div>
                    <div class="dataset-value">{{ datasetInfo.dataset_dir }}</div>
                </div>
                <div class="dataset-prop">
                    <div class="dataset-title">样本量</div>
                    <div class="dataset-value">{{ datasetInfo.labeled_samples }} / {{ datasetInfo.total_samples }}</div>
                </div>
                <div class="dataset-prop">
                    <div class="dataset-title">更新时间</div>
                    <div class="dataset-value">{{ datasetInfo.update_time }}</div>
                </div>
            </div>
            <div class="subset-title">配置训练/验证/测试集</div>
            <div v-for="(subset, index) in subsetsInfo" :key="subset.id">
                <div class="subset-info">
                    <div class="subset-type">{{ formattedSubsetType(subset.subset_type) }}</div>
                    <div class="subset-dir">
                        <FolderOpened v-if="!subset.editing && subset.image_dir" class="directory-item-title-icon yellow" />
                        <div v-if="!subset.editing">{{ subset.image_dir }}</div>
                    </div>
                    <el-select v-if="subset.editing" v-model="subset.image_dir" placeholder="选择数据集类型" size="small" style="width: 140" class="subset-select">
                        <el-option v-for="subset in subsetsDirs" :key="subset.id" :label="subset.image_dir" :value="subset.image_dir" />
                    </el-select>
                    <el-button type="primary" plain size="small" class="subset-btn" @click="onConfigSubset(subset)">{{ subset.editing ? '确定' : '编辑' }}</el-button>
                </div>
            </div>
            <div class="category-title">配置样本类别</div>
            <el-table
                :data="categories"
                highlight-current-row
                style="width: 100%"
                max-height="250"
                :header-cell-style="headerCellStyle"
                :cell-style="cellStyle"
                @row-click="handleRowClick"
                @row-dblclick="handleDbClick"
            >
                <el-table-column prop="category_id" label="id" width="50" />
                <el-table-column prop="category_name" label="category_name" min-width="100" />
                <el-table-column prop="supercategory" label="supercategory" min-width="100" />
            </el-table>
        </div>
        <template #footer>
            <el-button @click="onSettingConfirm(false)">关闭</el-button>
        </template>
    </el-dialog>
    <el-dialog v-model="categoryEditing" title="编辑类别" width="400">
        <el-form :model="category_form">
            <el-form-item label="Category Name">
                <el-input v-model="category_form.category_name" />
            </el-form-item>
            <el-form-item label="Super Category">
                <el-input v-model="category_form.supercategory" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="categoryEditing = false">取 消</el-button>
                <el-button type="primary" @click="onConfirmCategory"> 确 定 </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import API from '@/js/api';
import { onMounted, ref, watch, inject, reactive } from 'vue';

const emit = defineEmits(['settingConfirm']);
const props = defineProps(['openSettingVisible', 'datasetInfo']);
let vueApp = inject('vueApp');
function handleBeforeClose() {
    vueApp.monitorKeyEvent(true);
    emit('settingConfirm', false);
}

const openSettingVisible = ref(false);

// dataset和subset相关信息
const datasetInfo = ref({});
const subsetsInfo = ref({});
const subsetsDirs = ref([]);

// categories信息
const categories = ref([]);
let _current_index = ref(-1);

const categoryEditing = ref(false);
const category_form = ref({
    id: 0,
    category_name: '',
    supercategory: ''
});

watch(
    () => props.datasetInfo,
    async (newDataset, oldDataset) => {
        datasetInfo.value = props.datasetInfo;
        console.log(`setting dataset ${props.datasetInfo.id}`);
        // 读取所有的subset信息
        let result = await API.invoke('GetSubsets', { dataset_id: datasetInfo.value.id });
        console.log(result);
        if (result.code == 0) {
            subsetsInfo.value = result.msg
                .filter((subset) => subset.subset_type !== 'directory')
                .map((subset) => ({
                    ...subset,
                    editing: false
                }));
            subsetsDirs.value = result.msg.filter((subset) => subset.subset_type === 'directory');
            // console.log(`datasetInfo = `, datasetInfo.value);
            // console.log(`subsetsDirs = `, subsetsDirs.value);
        }

        // 读取所有的类别信息
        result = await API.invoke('GetCategories', { dataset_id: datasetInfo.value.id });
        if (result.code == 0) {
            categories.value = result.msg;
        }
    }
);

watch(
    () => props.openSettingVisible,
    (newVisible, oldVisible) => {
        openSettingVisible.value = props.openSettingVisible;
        vueApp.monitorKeyEvent(!props.openSettingVisible);
    }
);

function onSettingConfirm(confirm) {
    // openSettingVisible.value = false;
    emit('settingConfirm', confirm);
}

function formattedSubsetType(subset_type) {
    let types = {
        train: '训练集',
        val: '验证集',
        test: '测试集'
    };
    return types[subset_type];
}

async function onConfigSubset(subset) {
    console.log('onConfigSubset', subset);
    if (subset.editing == true) {
        let subset_directory = subsetsDirs.value.find((object) => object.image_dir === subset.image_dir);
        console.log('subset_directory = ', subset_directory);
        let subsetInfo = {
            id: subset.id,
            dataset_id: subset.dataset_id,
            image_dir: subset.image_dir,
            label_dir: subset_directory.label_dir
        };
        console.log(subsetInfo);
        let result = await API.invoke('UpdateSubset', subsetInfo);
        console.log(result);
        if (result.code == 0) {
            console.log(`result = `, result);
        }
    }
    subset.editing = !subset.editing;
}

async function onConfirmCategory() {
    console.log(`onConfirmCategory form = `, category_form.value);
    let result = await API.invoke('UpdateCategory', {
        id: category_form.value.id,
        category_name: category_form.value.category_name,
        supercategory: category_form.value.supercategory
    });
    if (result.code == 0) {
        result = await API.invoke('GetCategories', { dataset_id: datasetInfo.value.id });
        if (result.code == 0) {
            categories.value = result.msg;
        }
    }

    categoryEditing.value = false;
}
function handleDbClick(row, column, event) {
    console.log('handleDbClick event = ', row);
    category_form.value = {
        id: row.id,
        category_name: row.category_name,
        supercategory: row.supercategory
    };
    categoryEditing.value = true;
}
async function handleRowClick(row, column, event) {
    // console.log(`handleRowClick row = `, row);
    let rowIndex = categories.value.findIndex((item) => item.id === row.id);
    _current_index.value = rowIndex;
}

function headerCellStyle({ row, index }) {
    return {
        color: '#222',
        'background-color': '#efefef'
    };
}

function cellStyle({ row, column, rowIndex, columnIndex }) {
    // console.log(row, column, rowIndex, columnIndex);
    let style = {};

    // console.log(`row.id = ${row.id}, _current_index = ${_current_index.value}`);
    if (rowIndex == _current_index.value) {
        style['font-weight'] = 'bold';
    }

    return style;
}

onMounted(() => {});
</script>

<style scoped>
.setting-dialog {
    display: block;
}

.dataset-panel {
    /* width: 100%; */
    overflow: auto;
    border: solid 1px;
    border-color: #cfcfcf;
    /* box-shadow: 2px 2px 0px 0px rgba(229, 229, 232, 0.5); */
    /* box-shadow: inset 2px 2px 5px rgb(222, 226, 228); */
    padding: 5px;
}

.dataset-name {
    font-size: 16px;
    font-weight: 800;
    margin: 5px;
    white-space: nowrap;
}

.dataset-tags {
    margin: 5px;
}

.dataset-tag {
    margin-right: 5px;
}

.dataset-prop {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.dataset-title {
    flex: 0 0 auto;
    font-weight: 800;
    margin-left: 20px;
    color: rgb(151, 151, 151);
}

.dataset-value {
    flex: 1 1 auto;
    text-align: right;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: calc(100% - 100px);
    color: rgb(151, 151, 151);
    margin-right: 10px;
}

.subset-panel {
    width: 100%px;
    overflow: auto;
    box-shadow: 2px 2px 0px 0px rgba(229, 229, 232, 0.5);
    margin: 5px 0px;
    padding: 5px 5px;
}

.subset-title {
    font-size: 14px;
    font-weight: 800;
    margin: 15px 5px 5px 5px;
    white-space: nowrap;
}

.subset-info {
    display: flex;
    align-items: center;
    margin: 5px;
    width: 100%;
}

.subset-type {
    flex: 1;
    white-space: nowrap;
    font-weight: 800;
    overflow: hidden;
    text-overflow: ellipsis;
    color: rgb(151, 151, 151);
    margin-left: 15px;
}

.subset-dir {
    display: flex;
    margin: 0px 10px;
}

.subset-select {
    margin-right: 5px;
    flex-shrink: 0;
    width: 140px;
}

.directory-item-title-icon {
    padding: 0px 2px;
    width: 16px;
    height: 16px;
    color: rgb(223, 173, 36);
}

.subset-btn {
    margin-right: 15px;
}

.category-title {
    font-size: 14px;
    font-weight: 800;
    margin: 15px 5px 10px 5px;
    white-space: nowrap;
}
</style>
